package com.dao.impl;

import com.controller.FavourServlet;
import com.dao.BaseDao;

import com.dao.intf.FavourDao;
import com.entity.Blog;
import com.entity.Favour;

import java.util.List;

public class FavourDaoImpl extends BaseDao implements FavourDao {
    @Override
    public int saveFavour(Integer blogId, Integer userId) {
        String sql=" INSERT INTO `favour` (`blogId`,`userId`) VALUES(?,?)";
        String sql1="UPDATE `blog` SET `favour`=`favour`+1 WHERE id = ?";

        update(sql, blogId, userId);
        return update(sql1,blogId);

    }

    @Override
    public int deleteFavour(Integer blogId, Integer userId) {
        String sql=" DELETE FROM `favour` WHERE `blogId` = ? AND `userId`= ?";
        String sql1="UPDATE `blog` SET `favour`=`favour`-1 WHERE id =?";
         update(sql,blogId,userId);
        return update(sql1,blogId);
    }


    @Override
    public boolean isFavour(Integer blogId, Integer userId) {
        String sql="SELECT  * FROM `favour` WHERE `blogId`=? AND `userId`=?";
        List<Favour> favours = queryForList(Favour.class, sql, blogId, userId);
        if(favours.size()==0){
            //数据库里没查到，证明当前用户没有点赞当前博客
            return true;

        }else {
            //证明当前用户有点赞当前博客
            return false;
        }
    }

    @Override
    public List<Favour> queryFavourByBlogId(Integer blogId) {
        String sql="SELECT  `userId` FROM `favour` WHERE `blogId`=?";

        return  queryForList(Favour.class,sql,blogId);
    }

    @Override
    public Integer queryUserFavour(Integer userId) {
        String sql="SELECT `favour` FROM `blog` WHERE  `userId`=?";
        Integer userFavour=0;

        List<Blog> blogs = queryForList(Blog.class, sql, userId);
        for (Blog blog : blogs) {
            userFavour += blog.getFavour();
        }

        return userFavour;

    }


}
